package com.topvision.controller;

import com.alibaba.fastjson.JSONObject;
import com.topvision.common.response.ErrorResponse;
import com.topvision.common.response.SuccessResponse;
import com.topvision.common.security.UserInfo;
import com.topvision.common.security.UserInfoUtils;
import com.topvision.domain.ArRecPro;
import com.topvision.domain.FaceRec;
import com.topvision.dto.FaceRecDto;
import com.topvision.service.ArRecProService;
import com.topvision.service.FaceRecService;
import com.topvision.utils.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.security.Principal;
import java.time.LocalDate;
import java.util.*;

/**
 * 人脸识别控制类
 *
 * @author shengwm
 * @create 2018-04-24 17:58
 **/
@RestController
@RequestMapping("/face")
@Api(value = "人脸识别", description = "人脸识别相关操作")
@Slf4j
public class FaceRecController {

    @Autowired
    private FaceRecService faceRecService;

    @Autowired
    private ArRecProService arRecProService;

    @Autowired
    private UserInfoUtils userInfoUtils;

    @PostMapping("/addFace")
    public ResponseEntity addFace(HttpServletRequest request) {

        Map<String, Object> map = ArFileUtil.getFile(request, "file");
        InputStream ftpInputStream = (InputStream) map.get("ftpstream");
        File tmpFile = (File) map.get("file");

        Map<String, Object> parammap = new HashMap<>();
        String code = UUID.randomUUID().toString();
        parammap.put("file", tmpFile);
        parammap.put("filetag", code);
        JSONObject jsonObject = ArApiUtil.addSmartFace(parammap);
        if (jsonObject != null && jsonObject.get("value") != null && jsonObject.get("value").equals("SUCCESS")) {
            FaceRec faceRec = new FaceRec();
            if (StringUtils.isNotBlank(request.getParameter("groupId"))) {
                faceRec.setSysGroupId(Long.valueOf(request.getParameter("groupId")));
            }
            if (StringUtils.isNotBlank(request.getParameter("name"))) {
                faceRec.setName(request.getParameter("name"));
            }

            LocalDate today = LocalDate.now();
            String dir = today.toString().replace("-", "/");
            String name = (String) map.get("name");
            FtpConfigUtil.initFtp();
            try {
                FtpUtil.upload(ftpInputStream, name, Const.FTP_FACE_BASE_DIR + dir);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String imgUrl = Const.FTP_IMG_BASE_URL + "face/" + dir + "/" + name;
            faceRec.setUrl(imgUrl);
            faceRec.setCode(code);
            faceRecService.save(faceRec);
            return ResponseEntity.ok(SuccessResponse.of(faceRec));
        }
        return ResponseEntity.ok(ErrorResponse.of());
    }

    @PostMapping("/facePro")
    public ResponseEntity facePro(@RequestBody ArRecPro arRecPro) {
        if (arRecPro.getArRecId() != null) {
            arRecProService.save(arRecPro);
        }
        return ResponseEntity.ok(SuccessResponse.of(arRecPro));
    }

    @GetMapping("/faceList/{groupId}")
    public ResponseEntity faceList(@PathVariable String groupId, Principal principal) {
        UserInfo userInfo = userInfoUtils.getUserInfo(principal);
        Map<String, Object> params = new HashMap<>();
        params.put("createdBy", userInfo.getName());
        params.put("sysGroupId", Long.valueOf(groupId));
        List<FaceRec> faceRecs = faceRecService.list(params);
        return ResponseEntity.ok(SuccessResponse.of(faceRecs));
    }


    @PostMapping("/recFace")
    public ResponseEntity recFace(HttpServletRequest request, Principal principal) {
        UserInfo userInfo = userInfoUtils.getUserInfo(principal);
        Map<String, Object> map = ArFileUtil.getFile(request, "file");
        Map<String, Object> parammap = new HashMap<>();
        parammap.put("file", map.get("file"));
        JSONObject jsonObject = ArApiUtil.recSmartFace(parammap);
        String code = jsonObject.get("class_name").toString().trim();
        Map<String, Object> querymap = new HashMap<>();
        querymap.put("code", code);
        List<FaceRec> faceRecs = faceRecService.list(querymap);
        if (faceRecs != null && faceRecs.size() > 0) {
            FaceRec faceRec = faceRecs.get(0);

            Map<String, Object> queryRecProMap = new HashMap<>();
            queryRecProMap.put("arRecId", faceRec.getId());
            queryRecProMap.put("createdBy", userInfo.getName());
            List<ArRecPro> arRecPros = arRecProService.list(queryRecProMap);
            FaceRecDto faceRecDto = new FaceRecDto();
            faceRecDto.setCode(faceRec.getCode());
            faceRecDto.setName(faceRec.getName());
            faceRecDto.setUrl(faceRec.getUrl());
            faceRecDto.setArRecPros(arRecPros);
            faceRecDto.setRecResult(jsonObject);
            return ResponseEntity.ok(SuccessResponse.of(faceRecDto));
        }
        return ResponseEntity.ok(SuccessResponse.of());
    }

}
